﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ufida.u9.ait.openapi.utils;
using UFIDA.U9.CBO.Pub.Controller;
using UFIDA.U9.InvDoc.Enums;
using UFIDA.U9.InvDoc.MiscRcv;
using UFIDA.U9.InvDoc.MiscShip;
using UFIDA.U9.ISV.MiscShipISV;
using UFIDA.U9.ISV.MiscShipISV.Proxy;
using UFIDA.U9.Sn.Proxy;
using UFIDA.U9.Sn;
using UFIDA.U9.CBO.Enums;
using UFIDA.U9.CBO.SCM.Enums;
using UFIDA.U9.Lot;
using UFIDA.U9.Base.PropertyTypes;
using UFIDA.U9.CBO.SCM.Bin;
using UFSoft.UBF.Business;

namespace ufida.u9.ait.openapi
{
    internal class MiscShipBase
    {
        private static void preSave(IC_MiscShipmentDTOData dto)
        {
            foreach (IC_MiscShipmentLDTOData linedto in dto.MiscShipLs)
            {
                //校验
                if (linedto.ItemInfo == null)
                    throw new Exception("必须传入料品[ItemInfo]");
                if (linedto.Wh == null)
                    throw new Exception("必须传入仓库[Wh]");
                //货位处理
                if (linedto.MiscShipBins != null)
                {
                    foreach (IC_MiscShipBinDTOData bindto in linedto.MiscShipBins)
                    {
                        if (bindto.BinInfo == null)
                            throw new Exception("必须传入货位[BinInfo]");

                        Bin bin = EntityUtils.GetEntityByPath<Bin>($"Code='{bindto.BinInfo.Code}' and Warehouse.Code='{linedto.Wh.Code}'");
                        bindto.BinInfo.Bin = bin.ID;
                    }
                }
            }
        }

        public static MiscShipment CreateDoc(CopyOfIC_MiscShipmentDTOData dto)
        {
            IC_MiscShipmentDTOData dto1=new IC_MiscShipmentDTOData();
            DTOUtils.DTOPropCopy(dto, dto1);
            //需要先置空单号
            string docno = dto1.DocNo;
            dto1.DocNo = "";
            preSave(dto1);
            //新增逻辑,调用产业链服务
            CommonCreateMiscShipProxy proxy = new CommonCreateMiscShipProxy();
            proxy.ContextFrom = U9Utils.CreateContext();
            proxy.MiscShipmentDTOList = new List<IC_MiscShipmentDTOData>() { dto1 };
            List<CommonArchiveDataDTOData> ret = proxy.Do();
            MiscShipment doc = MiscShipment.Finder.FindByID(ret[0].ID);
            if (doc == null)
                throw new Exception("修改单号查找失败!");
            //创建序列号
            CreateSN(doc, dto);
            return doc;
        }

        private static void CreateSN(MiscShipment doc, CopyOfIC_MiscShipmentDTOData dto)
        {
            List<SnDocInfoDTOData> snDocInfoList = new List<SnDocInfoDTOData>();

            for (int i = 0; i < doc.MiscShipLs.Count; i++)
            {
                //每行处理
                MiscShipmentL line = doc.MiscShipLs[i];
                CopyOfIC_MiscShipmentLDTOData dtoline = dto.MiscShipLs[0];
                if (line.ItemInfo?.ItemID?.InventoryInfo?.SnParamKey == null) continue;
                if (line.Wh?.IsSerial != true) continue;

                if (line.MiscShipBins != null && line.MiscShipBins.Count > 0
                    && dtoline.MiscShipBins != null && dtoline.MiscShipBins.Count > 0)
                {
                    for (int j = 0; j < line.MiscShipBins.Count; j++)
                    {
                        //每行库位处理
                        MiscShipBin bin = line.MiscShipBins[j];
                        CopyOfIC_MiscShipBinDTOData dtobin = dtoline.MiscShipBins[j];
                        if (dtobin.SNList == null || dtobin.SNList.Count == 0) continue;
                        //构造SN DTO
                        SnDocInfoDTOData snDocInfo = GetSnDocInfoDTOData(line, bin, dtobin.SNList);
                        snDocInfoList.Add(snDocInfo);
                    }
                }
                else
                {
                    //无库位处理
                    if (dtoline.SNList1 == null || dtoline.SNList1.Count == 0) continue;
                    //构造SN DTO
                    SnDocInfoDTOData snDocInfo = GetSnDocInfoDTOData(line, null, dtoline.SNList1);
                    snDocInfoList.Add(snDocInfo);
                }
            }

            if (snDocInfoList.Count > 0)
            {
                CreateSnAfterDocCreateProxy proxy = new CreateSnAfterDocCreateProxy();
                proxy.SnDocInfoDTOList = snDocInfoList;
                proxy.Do();
            }
        }

        private static SnDocInfoDTOData GetSnDocInfoDTOData(MiscShipmentL line, MiscShipBin bin, List<string> sns)
        {
            SnDocInfoDTOData snDocInfoDTOData = new SnDocInfoDTOData();
            MiscShipment doc = line.MiscShip;

            //其他信息
            snDocInfoDTOData.DocName = MiscShipment.EntityRes.GetResource(MiscShipment.EntityRes.BE_FullName);
            snDocInfoDTOData.OperatorType = BusinessOperatorTypeEnum.NewCreate.Value;
            snDocInfoDTOData.DocTypeName = doc.DocType.Name;
            snDocInfoDTOData.ItemInfo = line.ItemInfo.ToEntityData();
            snDocInfoDTOData.SnClassType = 0;
            snDocInfoDTOData.UseOrg = line.Org.ID;
            snDocInfoDTOData.Usetime = doc.BusinessDate;
            snDocInfoDTOData.Wh = line.Wh.ID;
            snDocInfoDTOData.StoreUOM = line.StoreUOMKey.ID;
            snDocInfoDTOData.LogisticOrg = line.OrgKey.ID;
            snDocInfoDTOData.ItemOwnOrg = line.Org.ID;
            snDocInfoDTOData.DepositType = line.Wh.DepositType.Value;
            if (line.LotInfo != null)
            {
                //批号信息
                snDocInfoDTOData.LotInfo = LotMasterHelper.FromLotMasterInfoToLotInfoData(line.LotInfo);
            }
            if (line.SeibanKey != null)
            {
                snDocInfoDTOData.Seiban = line.SeibanKey.ID;
                snDocInfoDTOData.SeiBanNo = line.SeibanCode;
            }

            //单据信息
            snDocInfoDTOData.SnDocDTO = new SnDocDTOData();
            snDocInfoDTOData.SnDocDTO.Status = LotSnStatusEnum.I_MiscShipment.Value;
            snDocInfoDTOData.SnDocDTO.BizType = LotSnBizTypeEnum.I_MiscShip.Value;
            snDocInfoDTOData.SnDocDTO.Document = new BizEntityKeyData()
            {
                EntityID = doc.Key.ID,
                EntityType = doc.Key.EntityType,
            };
            snDocInfoDTOData.SnDocDTO.DocType = new BizEntityKeyData()
            {
                EntityID = doc.DocType.Key.ID,
                EntityType = doc.DocType.Key.EntityType,
            };
            snDocInfoDTOData.SnDocDTO.DocVersion = doc.Version;
            snDocInfoDTOData.SnDocDTO.DocNo = doc.DocNo;
            snDocInfoDTOData.SnDocDTO.DocLine = new BizEntityKeyData()
            {
                EntityID = line.Key.ID,
                EntityType = line.Key.EntityType,
            };
            snDocInfoDTOData.SnDocDTO.DocLineNo = line.DocLineNo;
            if (bin != null)
            {
                snDocInfoDTOData.SnDocDTO.DocSubLine = new BizEntityKeyData()
                {
                    EntityID = bin.Key.ID,
                    EntityType = bin.Key.EntityType,
                };
                snDocInfoDTOData.SnDocDTO.DocSubLineNo = line.DocLineNo;
                snDocInfoDTOData.BinInfo = new BinInfoData()
                {
                    Bin = bin.BinInfo.Bin.ID,
                    Code = bin.BinInfo.Code,
                    Name = bin.BinInfo.Name,
                };
            }

            //数量
            decimal Qty = line.StoreUOMQty;
            int Reault = 0;
            int.TryParse(Math.Truncate(Qty).ToString(), out Reault);
            snDocInfoDTOData.SnQty = Reault;
            snDocInfoDTOData.StoreQty = Qty;
            if (Qty != sns.Count) throw new Exception("数量与序列号个数不等!");

            //// 来源单据信息
            //if (line.SrcDocKey > 0L)
            //{
            //    snDocInfoDTOData.SrcSnDocDTO = new List<SnDocDTOData>();
            //    SnDocDTOData dto = new SnDocDTOData();
            //    dto.Document = new Base.PropertyTypes.BizEntityKeyData();
            //    dto.Document.EntityID = line.SrcDocKey;
            //    //dto.Document.EntityType = line.SrcDoc.SrcDoc.EntityType;
            //    dto.DocType = new Base.PropertyTypes.BizEntityKeyData();
            //    dto.DocType.EntityID = line.SrcDocTransType;
            //    //dto.DocType.EntityType =line.srcdoc line.SrcDoc.SrcDocTransType.EntityType;
            //    dto.DocNo = line.SrcDocNo;
            //    dto.DocLine = new Base.PropertyTypes.BizEntityKeyData();
            //    dto.DocLine.EntityID = line.SrcDocLineKey;
            //    //dto.DocLine.EntityType =;
            //    dto.DocLineNo = line.SrcDocLineNo;
            //    snDocInfoDTOData.SrcSnDocDTO.Add(dto);
            //}

            //构造返回DTO
            snDocInfoDTOData.SnDTOList = new List<SnDTOData>();
            foreach (var snCode in sns)
            {
                SnDTOData snDto = new SnDTOData();
                snDto.SnCode = snCode;
                snDto.SnDocInfoDTO = snDocInfoDTOData;
                snDocInfoDTOData.SnDTOList.Add(snDto);
            }
            return snDocInfoDTOData;
        }
        public static MiscShipment ApproveDocEx(DocDTOData dto, MiscShipment doc)
        {
            if (!String.IsNullOrEmpty(dto.DocDate))
            {
                //修改日期
                using(ISession session = Session.Open())
                {
                    doc.BusinessDate = DateTime.Parse(dto.DocDate);//单据日期
                    doc.SOBAccountPeriod = EntityUtils.getPostPeriod(doc.BusinessDate);//记账期间
                    if (doc.MiscShipAccountPeriods != null && doc.MiscShipAccountPeriods.Count > 0)
                    {
                        //记账期间
                        doc.MiscShipAccountPeriods[0].SOBAccountPeriod = doc.SOBAccountPeriod;
                    }

                    session.Commit();
                }
            }

            return ApproveDoc(doc);
        }
        public static MiscShipment ApproveDoc(MiscShipment doc)
        {
            if (doc.Status == INVDocStatus.Approved)
                throw new Exception($"单号：[{doc.DocNo}]状态为审核！");

            if(doc.Status == INVDocStatus.Open)
            {
                CommitDoc(doc);
            }

            U9Utils.ClearCache();
            CommonApproveMiscShipSV sv = new CommonApproveMiscShipSV();
            sv.MiscShipmentKeyList = new List<CommonArchiveDataDTO>()
            {
                new CommonArchiveDataDTO()
                {
                    ID = doc.ID,
                }
            };
            List<IC_MiscShipmentDTO> iC_MiscShipmentDTOs = sv.Do();

            return doc;
        }

        public static MiscShipment UnApproveDoc(MiscShipment doc)
        {
            if (doc.Status != INVDocStatus.Approved)
                throw new Exception($"单号：[{doc.DocNo}]状态不为审核！");

            CommonUnApporveMiscShipSV sv = new CommonUnApporveMiscShipSV();
            sv.MiscShipmentKeyList = new List<CommonArchiveDataDTO>()
            {
                new CommonArchiveDataDTO()
                {
                    ID = doc.ID,
                }
            };
            List<IC_MiscShipmentDTO> iC_MiscShipmentDTOs = sv.Do();

            return doc;
        }

        public static MiscShipment CommitDoc(MiscShipment doc)
        {
            if (doc.Status != INVDocStatus.Open)
                throw new Exception($"单号：[{doc.DocNo}]状态不为开立！");

            CommonCommitMiscShipSV sv = new CommonCommitMiscShipSV();
            sv.MiscShipmentKeyList = new List<CommonArchiveDataDTO>()
            {
                new CommonArchiveDataDTO()
                {
                    ID = doc.ID,
                }
            };
            List<IC_MiscShipmentDTO> iC_MiscShipmentDTOs = sv.Do();

            return doc;
        }
    }
}
